package com.wym.rbac.web.interceptor;

import com.wym.rbac.common.Constants;
import com.wym.rbac.domain.Employee;
import com.wym.rbac.domain.vo.R;
import com.wym.rbac.utils.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录认证拦截器
 * 对用户请求拦截
 * 验证是否登录，如果登录，方法继续执行
 * 如果没有登录，返回未授权信息
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跨域处理
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.setContentType("application/json;charset=utf-8");

        if (!(handler instanceof HandlerMethod)) { // 放行跨域的预检请求
            return true;
        }

        // 验证用户是否登录
        String userId = request.getHeader(Constants.USER_ID);
        Assert.notNull(userId, "非法操作");
        String employeeJson = redisUtils.get(Constants.LOGIN_EMPLOYEE + ":" + userId);
        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(employeeJson, Employee.class);

        // 判断登录对象是否为 null, 如果为 null, 未登录
        if (employee == null) {
            try {
                // 401 未授权
                response.getWriter().write(mapper.writeValueAsString(
                        R.error(HttpStatus.UNAUTHORIZED.value(), "没有登录")
                ));
                return false; // false: 拦截请求
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 已登录，放行
        return true;
    }
}
